package com.future.service;

import com.future.common.exception.AppException;
import com.future.dao.SysUserDao;
import com.future.model.SysUser;
import com.jfinal.aop.Inject;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

import cn.hutool.crypto.SecureUtil;

public class SysUserService {
	@Inject
	private SysUserDao sysUserDao;

	public void validateUser(String username, String password) {
		SysUser user = this.sysUserDao.findUserByUsername(username);
		if (user == null) {
			throw new AppException("用户[" + username + "]不存在!");
		}
		String passwordDb = user.getPassword();
		if (passwordDb == null || !passwordDb.equals(SecureUtil.md5(password))) {
			throw new AppException("密码错误!");
		}
	}

	public SysUser findUserById(String userid) {
		if (StrKit.isBlank(userid)) {
			throw new AppException("用户信息为空!");
		}
		return this.sysUserDao.findById(userid);
	}

	public void saveUser(String username, String userType, Long userinfoId) {
		SysUser sysUser = new SysUser();
		sysUser.setUsername(username);
		sysUser.setUserType(userType);
		sysUser.setUserinfoid(userinfoId);
		sysUser.setPassword(SecureUtil.md5(PropKit.get("defaultPassword")));
		sysUser.save();
	}

	public void checkUserNameExisted(String userName) {
		SysUser user = this.sysUserDao.findUserByUsername(userName);
		if (user != null) {
			throw new AppException("该登录名已经存在了");
		}
	}

	public void checkUserNameExisted(String userName, Long userid) {
		SysUser user = this.sysUserDao.findUserByUsername(userName);
		if (user != null && user.getUserid() != userid) {
			throw new AppException("该登录名已经存在了");
		}
	}
}
